package com.mainbo.modular.system.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.ClassInfoMessage;
import com.mainbo.modular.system.dao.PtClassMapper;
import com.mainbo.modular.system.dao.PtClassUserMapper;
import com.mainbo.modular.system.dao.PtStudentMapper;
import com.mainbo.modular.system.dao.PtTeacherMapper;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.service.IPtClassService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author moshang
 * @since 2020-02-24
 */
@Service
public class PtClassServiceImpl extends ServiceImpl<PtClassMapper, PtClass> implements IPtClassService {

    private static final Logger logger = LoggerFactory.getLogger(PtClassServiceImpl.class);
    @Resource
    private PtClassMapper classMapper;
    @Resource
    private PtClassUserMapper classUserMapper;
    @Resource
    private PtTeacherMapper teacherMapper;
    @Resource
    private JmsService jmsService;
    @Resource
    private PtStudentMapper studentMapper;

    @Override
    public List<PtClass> getClassList(PtClass ptClass) {
        List<PtClass> classList = classMapper.findList(ptClass);
        for (PtClass ci : classList) {
            EntityWrapper<PtClassUser> wrapper = new EntityWrapper<>();
            wrapper.eq("class_id", ci.getId());
            wrapper.eq("enable", 1);
            wrapper.eq("type", PtClassUser.TYPE_STUDENT);
            ci.setStudentCount(classUserMapper.selectCount(wrapper));
            if (ci.getPhaseId() != null) {
                ci.setPhase(MetaUtils.getMeta(ci.getPhaseId()).getName());
            }
            if (ci.getGradeId() != null) {
                ci.setGrade(MetaUtils.getMeta(ci.getGradeId()).getName());
            }
            if (ci.getClassType() != null) {
                ci.setClassTypeName(MetaUtils.getMeta(ci.getClassType()).getName());
            }
            ci.setPeriodName(ci.getPeriod() + "届");
        }
        return classList;
    }

    @Override
    public Result saveOrUpdateClass(PtClass ptClass, Result result) {
        PtAccount account = ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);// 当前登录账号
        if (StringUtils.isBlank(ptClass.getTeacherId())) {
            ptClass.setTeacherId("");
            ptClass.setTeacherName("");
        }
        ptClass.setEnable(true);
        String messageType = null;
        // 更新
        if (StringUtils.isNotBlank(ptClass.getId())) {
            ptClass.setLastupId(account.getUserInfo().getId());
            ptClass.setLastupDttm(new Date());
            ptClass.setId(ptClass.getId());
            classMapper.updateById(ptClass);
            result.setCode(Result.SUCCESS);
            result.setMsg("修改成功");
            // LoggerUtils.updateLogger(LoggerModule.ORGMANAGE, "组织机构管理——班级管理——更新班级信息，班级ID:{}", clss.getId());
            messageType = MessageTypes.CLASS_UPDATE.name();
        } else { // 保存
            if (StringUtils.isNotEmpty(ptClass.getTeacherId())) {
                Teacher teacher = getTeacher(ptClass);
                if (teacher == null) {
                    result.setMsg("该教师不存在，请修改");
                    result.setCode(Result.FAIL);
                    return result;
                } else {
                    ptClass.setTeacherName(teacher.getName());
                }
            }
            PtClass temp = getClassByName(ptClass);
            if (temp != null) {
                result.setMsg("当前年级下班级名称已经存在！请修改");
                result.setCode(Result.FAIL);
                return result;
            }
            result.setCode(Result.SUCCESS);
            result.setMsg("添加成功");
            ptClass.setCrtId(account.getUserInfo().getId());
            ptClass.setCrtDttm(new Date());
            if (ptClass.getSchoolYear() == null) {
                ptClass.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(ptClass.getOrgId()));
            }
            ptClass.setGraduationStatus(PtClass.not_graduation);
            ptClass.setStatus(PtClass.update_not_begin);
            classMapper.insert(ptClass);
            //LoggerUtils.insertLogger(LoggerModule.ORGMANAGE, "组织结构管理——班级管理——新增班级信息，班级ID:{}", clss.getId());
            messageType = MessageTypes.CLASS_INSERT.name();
        }
        // 发送消息
        ClassInfoMessage classVo = new ClassInfoMessage();
        try {
            BeanUtils.copyProperties(ptClass, classVo);
        } catch (Exception e) {
            logger.error("clss copy error", e);
        }
        classVo.setMessageType(messageType);
        jmsService.sendMessage(classVo);
        return  result;
    }

    public Teacher getTeacher(PtClass clss) {
        Teacher param = new Teacher();
        param.setId(clss.getTeacherId());
        Teacher teacher = teacherMapper.selectOne(param);
        return teacher;

    }

    @Override
    public PtClass getClassByName(PtClass ptClass) {
        PtClass ci = new PtClass();
        ci.setName(ptClass.getName());
        ci.setPhaseId(ptClass.getPhaseId());
        ci.setGradeId(ptClass.getGradeId());
        ci.setOrgId(ptClass.getOrgId());
        ci.setSchoolYear(ptClass.getSchoolYear());
        ci.setEnable(true);
        return classMapper.selectOne(ci);
    }

    @Override
    public void deleteClass(String id) {
        PtClass classInfo = classMapper.selectById(id);
        if (classInfo == null) {
            return;
        }
        classMapper.deleteById(id);
        // 同时删除班级和任课教师、学生的关联关系
        EntityWrapper<PtClassUser> cu = new EntityWrapper<>();
        cu.eq("class_id", id);
        List<PtClassUser> classUserList = classUserMapper.selectList(cu);
        for (PtClassUser classUser : classUserList) {
            classUserMapper.deleteById(classUser.getId());
        }
        //  LoggerUtils.deleteLogger(LoggerModule.ORGMANAGE, "组织机构管理——班级管理——删除班级信息，班级ID:{}", id);
        // 发送消息
        try {
            ClassInfoMessage classInfoVo = new ClassInfoMessage();
            classInfoVo.setId(id);
            classInfoVo.setMessageType(MessageTypes.CLASS_DELETE.name());
            classInfoVo.setOrgId(classInfo.getOrgId());
            classInfoVo.setSchoolYear(classInfo.getSchoolYear());
            jmsService.sendMessage(classInfoVo);
        } catch (Exception e) {
            logger.error("组织机构管理——班级管理——删除班级——发送消息失败", e);
        }
    }

    @Override
    public List<PtClass> getAllclasses(String orgId, Integer phaseId, Integer gradeId, Integer schoolYear) {
        EntityWrapper<PtClass> model = new EntityWrapper<>();
        model.eq("org_id", orgId);
        model.eq("phase_id", phaseId);
        model.eq("grade_id", gradeId);
        model.eq("school_year", schoolYear);
        model.lt("graduation_status", PtClass.school_graduation);
        List<PtClass> classInfos = this.selectList(model);
        return classInfos;
    }

    @Override
    public List<PtClass> getSelectedclasses(String orgId, Integer phaseId, Integer gradeId, String classIds, Integer schoolYear) {
        EntityWrapper<PtClass> model = new EntityWrapper<>();
        if (StringUtils.isNotEmpty(classIds)) {
            List<String> clssList = Arrays.asList(classIds.split(","));
            model.in("id", clssList);

        } else {
            if (StringUtils.isNotBlank(orgId)) {
                model.eq("org_id", orgId);
            }
            if (phaseId != null) {
                model.eq("phase_id", phaseId);
            }
            if (gradeId != null) {
                model.eq("grade_id", gradeId);
            }
            if (schoolYear != null) {
                model.eq("school_year", schoolYear);
            }

            model.ge("status", PtClass.update_begin);
        }
        List<PtClass> classInfos = this.selectList(model);
        return classInfos;
    }

    @Override
    public void changeClassStatus(String classIds, Integer status) {
        if (StringUtils.isNotEmpty(classIds)) {
            String[] idArray = classIds.split(",");
            for (String classId : idArray) {
                PtClass classInfo = this.selectById(classId);
                if (classInfo != null) {
                    if (classInfo.getStatus() == null) {
                        classInfo.setStatus(PtClass.update_not_begin);
                    }
                    if (status != null && (status > classInfo.getStatus())) {
                        classInfo.setStatus(status);
                        this.updateById(classInfo);
                    }
                }
            }
        }
    }

    @Override
    public void chanageStudentGraduationStatus(List<String> userIds, Integer graduationStatus) {
        studentMapper.changeStudentGraduationStatus(userIds,graduationStatus);
    }

    @Override
    public List<String> changeClassinfoGraduation(Set<String> classIds, Integer status) {
        List<String> changeClassIds = new ArrayList<String>();
        if (classIds != null) {
            for (String classId : classIds) {
                PtClass classInfo = this.selectById(classId);
                if (classInfo != null) {
                    if (!status.equals(classInfo.getGraduationStatus())) {
                        classInfo.setGraduationStatus(status);
                        this.updateById(classInfo);
                        changeClassIds.add(classId);
                    }
                }
            }
        }
        return changeClassIds;
    }
}
